package com.jolink.omiis.wechat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JacksonJsonParser;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jolink.omiis.wechat.outer.IWeChatQuery;

public class WeChatQuery implements IWeChatQuery {
	private static Logger logger = LoggerFactory.getLogger(WeChatQuery.class);
	private String appid = "wx7b9786318bf71dad";
	private String secret = "847b0e4516816749339f0b3ce4270913";
	private String access_token = "R3TH48ZuaeXgA8Oclt8FdtTBo0NHjBDaUtV33H0Z5b6vZYe-33puAm5nNSIZ5EpEYFzk9Zp1XLLq1J3wugq8WjShRul8NoKtuDhsBOv7w_tDkjQUlPZQUGb-ZQGUBzPqMVHiAGDUDP";

//	public static void main(String[] args) {
//		WeChatQuery wcq = new WeChatQuery();
//		// wcq.queryAccess_token(null);
//		// wcq.queryTencent_ip(null);
////		wcq.createMenu(null);
//		 wcq.queryMenu(null);
//		// wcq.delMenu(null);
//	}

	@Override
	public Map<String, Object> queryAccess_token(Map<String, String> paramMap) {
		HttpClient client = new DefaultHttpClient();

		HttpUriRequest request = new HttpGet(
				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
						+ secret);
		HttpResponse response = null;
		Map<String, Object> resultMap = null;
		try {
			long t1 = System.currentTimeMillis();
			response = client.execute(request);
			if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				logger.info("请求腾讯服务获取响应成功，耗时：" + (System.currentTimeMillis() - t1) + "毫秒。");
			}
			HttpEntity httpEntity = response.getEntity();
			String body = EntityUtils.toString(httpEntity);
			JacksonJsonParser parser = new JacksonJsonParser();
			resultMap = parser.parseMap(body);
			logger.info("读取响应内容：" + body);
			logger.info("实际内容大小：" + body.getBytes().length);
			logger.info("将结果转换成 Map：" + resultMap);
			logger.info("返回内容大小：" + httpEntity.getContentLength());
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	@Override
	public List<Object> queryTencent_ip(Map<String, String> paramMap) {
		HttpClient client = new DefaultHttpClient();
		HttpUriRequest request = new HttpGet(
				"https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + access_token);
		HttpResponse response = null;
		Map<String, Object> resultMap = null;
		try {
			long t1 = System.currentTimeMillis();
			response = client.execute(request);
			if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				logger.info("请求腾讯服务获取响应成功，耗时：" + (System.currentTimeMillis() - t1) + "毫秒。");
			}
			HttpEntity httpEntity = response.getEntity();
			String body = EntityUtils.toString(httpEntity);
			JacksonJsonParser parser = new JacksonJsonParser();
			resultMap = parser.parseMap(body);
			logger.info("读取响应内容：" + body);
			logger.info("实际内容大小：" + body.getBytes().length);
			logger.info("将结果转换成 Map：" + resultMap);
			logger.info("返回内容大小：" + httpEntity.getContentLength());
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return (List<Object>) resultMap.get("ip_list");
	}

	@Override
	public Map createMenu(Map paramMap) {
		HttpClient client = new DefaultHttpClient();

		HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token);
		// post.addHeader("Content-Type", "application/json;charset=UTF-8");
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		JsonArray array = new JsonArray();
		JsonObject button = new JsonObject();
		button.add("button", array);
		// JsonObject button = new JsonObject();

		{
			JsonObject button1 = new JsonObject();
			button1.addProperty("name", "关于58");
			JsonArray array1 = new JsonArray();
			JsonObject subButton_1 = new JsonObject();
			subButton_1.addProperty("type", "view");
			subButton_1.addProperty("name", "注册绑定");
			subButton_1.addProperty("url", "http://www.58.com");
			String redirectURl=null;
			try {
				redirectURl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7b9786318bf71dad&redirect_uri="
						+ URLEncoder.encode("http://www.acefet.com/customer/query","utf-8")
						+ "&response_type=code&scope=snsapi_base&state=abcdefg9527jolink#wechat_redirect";
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			;
			subButton_1.addProperty("url", redirectURl);
			// subButton_1.addProperty("url",
			// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7b9786318bf71dad&redirect_uri=http://www.acefet.com/customer/register&response_type=code&scope=snsapi_base&state=abcdefg9527jolink#wechat_redirect");
			// subButton_1.addProperty("url",
			// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7b9786318bf71dad&redirect_uri\\=http://www.58.com&response_type\\=code&scope\\=snsapi_base&state\\=abcdefg9527jolink#wechat_redirect");
			array1.add(subButton_1);
			button1.add("sub_button", array1);
			// button.add("button", button1);
			array.add(button1);
		}
		{
			JsonObject button2 = new JsonObject();
			button2.addProperty("name", "58");
			JsonArray array1 = new JsonArray();
			JsonObject subButton_1 = new JsonObject();
			subButton_1.addProperty("type", "view");
			subButton_1.addProperty("name", "58钱柜");
			subButton_1.addProperty("url", "http://58.com");
			array1.add(subButton_1);
			button2.add("sub_button", array1);
			// button.add("button", button2);
			array.add(button2);
		}
		// {
		// JsonObject button3 = new JsonObject();
		// button3.addProperty("name", "一日游");
		// JsonArray array1 = new JsonArray();
		// JsonObject subButton_1 = new JsonObject();
		// subButton_1.addProperty("type", "view");
		// subButton_1.addProperty("name", "北京公交");
		// subButton_1.addProperty("url", "http://baidu.com");
		// array1.add(subButton_1);
		// button3.add("sub_button", array1);
		// // button.add("button", button3);
		// array.add(button3);
		// }

		String menuJson = gson.toJson(button);
		logger.info("menuJson=" + menuJson);
		StringEntity entity = null;
		try {
			entity = new StringEntity(menuJson, "UTF-8");
			entity.setContentType("text/json");

			post.setEntity(entity);
			HttpResponse response = client.execute(post);
			HttpEntity responseBody = response.getEntity();
			String responseStr = EntityUtils.toString(responseBody);
			logger.info("返回信息：" + responseStr);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}

		return null;
	}

	@Override
	public Map delMenu(Map paramMap) {
		HttpClient client = new DefaultHttpClient();

		HttpGet get = new HttpGet("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + access_token);
		get.addHeader("Content-Type", "application/json; encoding=utf-8");

		try {

			HttpResponse response = client.execute(get);
			HttpEntity responseBody = response.getEntity();
			String responseStr = EntityUtils.toString(responseBody, "utf-8");

			logger.info("返回信息：" + responseStr);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return null;
	}

	@Override
	public Map queryMenu(Map paramMap) {
		HttpClient client = new DefaultHttpClient();

		HttpGet get = new HttpGet("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + access_token);
		get.addHeader("Content-Type", "application/json; encoding=utf-8");

		try {

			HttpResponse response = client.execute(get);
			HttpEntity responseBody = response.getEntity();
			String responseStr = EntityUtils.toString(responseBody, "utf-8");
			logger.info("返回信息：" + responseStr);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return null;
	}
}
